// package-store/pages/store-earning-record/index.js
const app = getApp();
import { ManageTargetInfoUpdateMixins, PageScrollListMixins } from '../../../behaviors/page';
import { ACCOUNT_LOG_CATEGORY } from '../../../constants/common';
import { PACKAGE_STORE_PAGE } from '../../../constants/route';
import { navToAction, showLoading, hideLoading } from '../../../common/env';
import { getDateTS } from '../../../common/utils';
import { getAggrAccountLogsToInOut, getAccountLogList } from '../../../api/sto';

Page({
    mixins: [ManageTargetInfoUpdateMixins, PageScrollListMixins],
    data: {
        aggrData: {},
        filter: {
            begin: getDateTS(null, false, 'month'),
            end: getDateTS(null, true, 'month'),
        },
    },
    onLoad(options) {
    },
    onShow() {
        this._handleGetAggr();
    },
    async _handleGetAggr() {
        const { filter } = this.data;
        const params = { ...filter };
        const aggrData = await getAggrAccountLogsToInOut(params);
        this.setData({ aggrData });
    },
    async _handleGetList(pageNo) {
        !this.data.loaded && showLoading('加载中...');
        const { pageData, filter } = this.data;
        let { ts } = pageData;
        pageNo === 1 && (ts = Date.now());
        const { rows = [], total } = await getAccountLogList({ pageNo, ts, ...filter });
        this.setData({
            pageData: {
                ...pageData,
                refresh: false,
                ts,
                pageNo,
                total,
                rows: pageNo == 1 ? rows : [...pageData.rows, ...rows],
            },
        });
        if (!this.data.loaded) hideLoading(); this.setData({ loaded: true });
    },
    handleChangeDate(e) {
        const { year, month } = e.detail;
        const date = `${year}-${month}-01`;
        console.log('EarningRecord => 年月改变', year, month);
        this.setData({
            filter: {
                begin: getDateTS(date, false, 'month'),
                end: getDateTS(date, true, 'month'),
            }
        });
        this._handleGetAggr();
        this._handleGetList(1);
    },
    handleNavToDetail(e) {
        const { rows } = this.data.pageData;
        const info = rows.find(i => i.id === e.detail);
        if (info.category !== ACCOUNT_LOG_CATEGORY.redemption) {
            navToAction(PACKAGE_STORE_PAGE['storeEarningDetail'], {}, {
                success(res) {
                    setTimeout(() => {
                        app.event.trigger('sendAccountLogInfo', info);
                    }, 800);
                },
            });
        }
    },
})
